﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Notification;
using System.Diagnostics;
using System.ServiceModel;
using OuSuisJeWorkerRole;

namespace AOuSuisJeWP7
{
    public class PushManager
    {
        private HttpNotificationChannel myChannel;

        public void SetupChannel()
        {
            myChannel = HttpNotificationChannel.Find("MyChannel");

            if (myChannel == null)
            {
                // Only one notification channel name is supported per application.
                myChannel = new HttpNotificationChannel("MyChannel", "www.findwhere.me");

                SetUpDelegates();

                // After myChannel.Open() is called, the notification channel URI will be sent to the application through the ChannelUriUpdated delegate.
                // If your application requires a timeout for setting up a notification channel, start it after the myChannel.Open() call. 
                myChannel.Open();
            }
            else // Found an existing notification channel.
            {
                SetUpDelegates();

                // The URI that the application sends to its web service.
                Debug.WriteLine("Notification channel URI:" + myChannel.ChannelUri.ToString());

                if (myChannel.ChannelUri == null)
                {
                    // The notification channel URI has not been sent to the client. Wait for the ChannelUriUpdated delegate to fire.
                    // If your application requires a timeout for setting up a notification channel, start it here.
                }
            }

            // An application is expected to send its notification channel URI to its corresponding web service each time it launches.
            // The notification channel URI is not guaranteed to be the same as the last time the application ran. 
            if (myChannel.ChannelUri != null)
            {
                SendURIToService(myChannel.ChannelUri);
            }

        }

        /// <summary>
        /// Envoi l'uri du channel PUSH au webservice
        /// </summary>
        /// <param name="uri"></param>
        private void SendURIToService(Uri uri)
        {
            EndpointAddress endpointAddr = new EndpointAddress("http://127.0.0.1:5126/PushNotificationService");

            ChannelFactory<IPushNotificationService> channelFactory = new ChannelFactory<IPushNotificationService>(new BasicHttpBinding(BasicHttpSecurityMode.None), endpointAddr);

            IPushNotificationService client = channelFactory.CreateChannel(endpointAddr);

            client.SetupNotificationUri(uri.AbsoluteUri);
        }

        public void SetUpDelegates()
        {
            myChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(myChannel_ChannelUriUpdated);
            myChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(myChannel_HttpNotificationReceived);
            myChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(myChannel_ShellToastNotificationReceived);
            myChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(myChannel_ErrorOccurred);
        }

        /// <summary>
        /// Réception d'une notification toast
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Erreur au sein du channel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            switch (e.ErrorType)
            {
                case ChannelErrorType.ChannelOpenFailed:
                    throw new Exception(string.Format("Impossible d'ouvrir le channel. ErrorCode : {0} ErrorType : {1}", e.ErrorCode, e.ErrorType));
                case ChannelErrorType.MessageBadContent:
                    throw new Exception(string.Format("Le contenu du message n'est pas correct. ErrorCode : {0} ErrorType : {1}", e.ErrorCode, e.ErrorType));
                case ChannelErrorType.NotificationRateTooHigh:
                    // ...
                    break;
                case ChannelErrorType.PayloadFormatError:
                    // ...
                    break;
                case ChannelErrorType.PowerLevelChanged:
                    // ...
                    break;
            }
        }

        /// <summary>
        /// Réception d'une notification raw
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Récupération de l'URI du channel permettant d'envoyer les notifications
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            Debug.WriteLine("Notification channel URI:" + myChannel.ChannelUri.ToString());

            SendURIToService(e.ChannelUri);
        }
    }
}
